task-managment / src / app / dashboard / projects / [...id] / _components / DownloadPdfInvoice.tsx
DownloadPdfInvoice.tsx
Raw
"use client";
import React from "react";
import jsPDF from "jspdf";
import autoTable from "jspdf-autotable";
import { Button } from "@/components/ui/button";
import { trpc } from "@/app/_trpc/client";

const DownloadPdfInvoice = ({ id }: { id: string }) => {
  const { data: project } = trpc.projects.getProjectById.useQuery({value:id}, {
    refetchOnMount: false,
    refetchOnWindowFocus: false,
  });

  const generatePDF = () => {
    const doc = new jsPDF();

    // Añadir encabezado
    doc.setFontSize(22);
    doc.text("Cotización", 14, 22);

    // Añadir contenido corto
    doc.setFontSize(12);
    doc.text("Lista de materiales y areas a trabajar en este projecto.", 14, 32);

    const materials = project?.projectMaterials.map(
      ({ requiredQuantity, materials }, index) => {
        const materialName = materials.name;
        const price = materials.price;
        return [ materialName, requiredQuantity, price];
      }
    );

    // Definir las columnas y las filas para la tabla
    const columns = ["Material", "Cantidad requerida", "Precio"];

    doc.setFontSize(16);
    doc.text("Materiales", 14, 45);
    // Generar la tabla con autoTable
    autoTable(doc, {
      startY: 48,
      head: [columns],
      body: materials,
    });

    // Definir las columnas y las filas para la tabla
    const columnsAreas = ["Piso", "Area", "Ancho", "Largo"];

    const areasRows = project?.floor
      .map(({ name, areas }) => {
        return areas.map(({ type, width, length }, index) => {
          return [name, type, width, length];
        });
      })
      .flat();

      doc.setFontSize(16);
      doc.text("Areas", 14, 84);
    // Generar la tabla con autoTable
    autoTable(doc, {
      startY: 86,
      head: [columnsAreas],
      body: areasRows,
    });

    // Descargar el PDF

    doc.save("invoice.pdf");
  };

  return (
    <div>
      <Button size="sm" onClick={generatePDF}>Download Invoice</Button>
    </div>
  );
};

export default DownloadPdfInvoice;